import { Context, Next } from 'koa';
import { validate, ValidationError } from 'class-validator';
import { plainToInstance } from 'class-transformer';
import { HttpError } from './errorHandler';
/**
 * DTO 验证中间件
 */
export const validateDto = (DtoClass: any, options: { skipMissingProperties?: boolean } = {}) => {
  return async (ctx: Context, next: Next) => {
    try {
      // 获取请求体数据
      const data = ctx.request.body as Record<string, any>;
      const { _id } = ctx.state.user;

      // 转换为 DTO 实例
      const dto = plainToInstance(DtoClass, data) as Record<string, any>;
      dto.updatedBy = _id.toString();
      dto.createdBy = _id.toString();


      // 执行验证
      const errors = await validate(dto, {
        skipMissingProperties: options.skipMissingProperties || false, // 允许缺失属性
        whitelist: true,  // 删除非法字段，不报错
        forbidNonWhitelisted: false // 发现非法字段 → 直接报错
      });

      // 如果有验证错误
      if (errors.length > 0) {
        const errorMessages = errors.map((error: ValidationError) => {
          if (error.constraints) {
            return Object.values(error.constraints).join(', ');
          }
          return `${error.property} 验证失败`;
        });

        throw HttpError.unprocessableEntity('数据验证失败validate', errorMessages);
      }


      console.log(dto, 'dto')
      // 验证通过，将验证后的数据存储在上下文中
      ctx.state.validatedData = dto;
      console.log('通过验证', dto)
      await next();
    } catch (error: any) {
      throw error;
    }
  };
};
